package com.company.cloud.coupon.modules.app.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.coupon.constant.CouponConstant.CouponStateEnum;
import com.company.cloud.coupon.constant.CouponConstant.CouponUsableObjTypeEnum;
import com.company.cloud.coupon.modules.app.controller.req.CouponInfoDrawParam;
import com.company.cloud.coupon.modules.app.controller.req.CouponInfoQuery4PageParam;
import com.company.cloud.coupon.modules.app.controller.req.CouponListByOrderParam;
import com.company.cloud.coupon.modules.app.controller.req.CouponMyQuery4PageParam;
import com.company.cloud.coupon.modules.app.service.CouponService;
import com.company.cloud.coupon.modules.base.entity.CouponConfigInfo;
import com.company.cloud.coupon.modules.base.entity.CouponInfo;
import com.company.cloud.coupon.modules.base.service.CouponConfigInfoService;
import com.company.cloud.coupon.modules.base.service.CouponInfoService;
import com.company.cloud.coupon.modules.cache.models.CouponConfigModel;
import com.company.cloud.coupon.modules.cache.models.CouponModel;
import com.company.cloud.coupon.modules.cache.utils.CouponChangeUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 优惠券
 */
@Login
@RestController
@RequestMapping("/app/op/coupon")
@Api(tags="OP_App_优惠券")
public class CouponInfoController {


	@Autowired
	private CouponConfigInfoService couponConfigInfoService;
	@Autowired
	private CouponInfoService couponInfoService;
	@Autowired
	private CouponService couponService;
	
	
	@PostMapping("/queryMyCoupon")
	@ApiOperation(value="查询我的优惠券", response=CouponModel.class)
	public BaseResult queryMyCoupon(@RequestBody CouponMyQuery4PageParam params) {
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		String _state=null;
		List<String> _states=new ArrayList<String>();
		if(StringUtils.hasText(params.getState())) {
			if("0".equals(params.getState())) {
				_state=CouponStateEnum.Not_CouponState.getCode();
			}else if("2".equals(params.getState())) {
				_state=CouponStateEnum.Overdue_CouponState.getCode();
			}else if("1".equals(params.getState())) {
				_states.add(CouponStateEnum.Lock_CouponState.getCode());
				_states.add(CouponStateEnum.Yes_Scan_CouponState.getCode());
				_states.add(CouponStateEnum.Yes_Pay_CouponState.getCode());
			}
		}
		IPage<CouponInfo> page = couponInfoService.page(
				new Page<>(params.getPage(), params.getRows()), 
				new QueryWrapper<CouponInfo>()
				.eq("have_user_id", userInfo.getId())
				.eq(StringUtils.hasText(_state), "state", _state)
				.in(CheckUtils.hasList(_states), "state", _states)
				.orderByAsc("company_no","end_date")
				);
		IPage<CouponModel> data=page.convert(new Function<CouponInfo, CouponModel>() {
			@Override
			public CouponModel apply(CouponInfo entity) {
				return CouponChangeUtils.getCoupon(entity,null);
			}
		});
		return BaseResult.ok(data);
	}
	
	@PostMapping("/getCouponByOrder")
	@ApiOperation(value="根据订单查询我的可使用优惠券", response=CouponModel.class)
	public BaseResult getCouponByOrder(@RequestBody CouponListByOrderParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
//		LoginUserInfo userInfo=new LoginUserInfo();
//		userInfo.setId(2);
		List<CouponModel> data= couponService.getMyCouponByOrder(params, userInfo);
		return BaseResult.ok(data);
	}
	
	
	@GetMapping("/get")
	@ApiOperation(value="获取", response=CouponModel.class)
	public BaseResult get(@RequestParam("couponNo")String couponNo) {
		CouponInfo coupon=couponInfoService.getById(couponNo);
		if(coupon==null) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		CouponConfigInfo couponConfig=couponConfigInfoService.getById(coupon.getCouponConfigId());
		CouponModel data=CouponChangeUtils.getCoupon(coupon, null,couponConfig);
		return BaseResult.ok(data);
	}
	
	
	@GetMapping("/getCouponConfig")
	@ApiOperation(value="获取优惠券配置信息", response=CouponConfigModel.class)
	public BaseResult getCouponConfig(@RequestParam("id")Integer id) {
		CouponConfigInfo couponConfig=couponConfigInfoService.getById(id);
		if(couponConfig==null || EnabledEnum.DISABLED.getCode().equals(couponConfig.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		if(!YNEnum.YES.getCode().equals(couponConfig.getUpperLowerState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		CouponConfigModel model= CouponChangeUtils.getCouponConfig(couponConfig);
		return BaseResult.ok(model);
	}
	
	
	@PostMapping("/queryCouponConfig")
	@ApiOperation(value="查询可领取的优惠券列表", response=CouponConfigModel.class)
	public BaseResult queryCouponConfig(@RequestBody CouponInfoQuery4PageParam params) {
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		IPage<CouponConfigInfo> page = couponConfigInfoService.page(
				new Page<>(params.getPage(), params.getRows()), 
				new QueryWrapper<CouponConfigInfo>()
				.eq("rows_state", EnabledEnum.ENABLED.getCode())
				.eq("upper_lower_state", YNEnum.YES.getCode())
				.eq("company_no", userInfo.getCompanyNo())
				.eq(StringUtils.hasText(params.getTitle()), "title", params.getTitle())
				.eq(StringUtils.hasText(params.getCouponType()), "coupon_type", params.getCouponType())
				.and(StringUtils.hasText(params.getProductNo()),
						i->i.eq("usable_obj_type", CouponUsableObjTypeEnum.All_UsableObj.getCode())
						.or(
							 j->j.eq("usable_obj_type", CouponUsableObjTypeEnum.Appointed_UsableObj.getCode())
							    .like("usable_obj_no", params.getProductNo())
							)	
					)
				.orderByAsc("company_no")
				);
		
		IPage<CouponConfigModel> data=page.convert(new Function<CouponConfigInfo, CouponConfigModel>() {
			@Override
			public CouponConfigModel apply(CouponConfigInfo entity) {
				return CouponChangeUtils.getCouponConfig(entity);
			}
		});
		
		return BaseResult.ok(data);
	}
	
	@PostMapping("/drawCoupon")
	@ApiOperation(value="领取优惠券", response=CouponModel.class)
	public BaseResult drawCoupon(@RequestBody CouponInfoDrawParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		CouponInfo coupon= couponService.collectCoupon(userInfo.getId(), params.getCouponConfigId(), userInfo);
		CouponModel data=CouponChangeUtils.getCoupon(coupon, null);
		return BaseResult.ok(data);
	}
	
}
